//
//  CrossSlipViewController.m
//  shise
//
//  Created by 徐国庆 on 14/12/17.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "CrossSlipViewController.h"
#import "CrossSlipCell.h"
#import "NetHandler.h"
#import "Food.h"
#import "Scroll.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "CrossSlipDetailViewController.h"
#import "ViewController.h"
#import "ApplyBuildActivityViewController.h"
#import "CrossSlipDetailOneCell.h"
#import "GoodShopViewController.h"
#import "GoodShopDetailViewController.h"

@interface CrossSlipViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)UITableView *tableView;
// 定义数组装数据处理之后的scroll对象
@property(nonatomic, retain)NSMutableArray *array;

@property(nonatomic, retain)NSString *refresh;

@end

@implementation CrossSlipViewController

// 初始化数组
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.array = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor blackColor];
    self.tableView.backgroundColor = [UIColor blackColor];
    
    self.view.backgroundColor = [UIColor redColor];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
//    [self handleData];
    
    [self setupRefresh];
    
    self.title = @"活动";
    
}

// 设置cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

// 设置cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        
        NSString *strr = @"aa";
        CrossSlipDetailOneCell *cell = [tableView dequeueReusableCellWithIdentifier:strr];
        if (cell == nil) {
            
            cell = [[[CrossSlipDetailOneCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strr]autorelease];
            
        }
        Scroll *scroll = [self.array objectAtIndex:indexPath.row];
        if ([scroll.type isEqualToString:@"ImageCard"]) {
            
            [cell.activityImageView setImageWithURL:[NSURL URLWithString:scroll.pic_url]];
            [cell.userHeadImageViewButton addTarget:self action:@selector(goodShopButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
            
        } else {
            
            return cell;
        }
        
    } else {
    
        NSString *string = @"ss";
        CrossSlipCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (cell == nil) {
        
            cell = [[[CrossSlipCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string]autorelease];
        
        }
        Scroll *scroll = [self.array objectAtIndex:indexPath.row];
        cell.activityImageView.image = [UIImage imageNamed:@"activity.png"];
        cell.numberOfPhotosAndEndDate.text = scroll.desc;
        cell.activityNameLabel.text = scroll.title;
        [cell.crossSlipButton addTarget:self action:@selector(crossSlipButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.crossSlipButton.tag = 5000 + indexPath.row;
       for (int i = 0; i < scroll.pics.count; i ++) {
        
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * 155, 5, 150, 150)];
            NSDictionary *dic = [scroll.pics objectAtIndex:i];
            NSString *ss = [dic objectForKey:@"url"];
            [imageView setImageWithURL:[NSURL URLWithString:ss]];
            [cell.scrollView addSubview:imageView];
            [imageView release];
        
    }
    return cell;
    }
}

// 点击横向滑动按钮事件
- (void)crossSlipButtonAction:(UIButton *)button
{
//    Scroll *scroll = [self.array objectAtIndex:button.tag - 5000];
//    GoodShopDetailViewController *goodShopDetailVC = [[GoodShopDetailViewController alloc] init];
//    goodShopDetailVC.address = scroll.api;
//    [self.navigationController pushViewController:goodShopDetailVC animated:YES];
//    [goodShopDetailVC release];
    
    Scroll *tempScroll = [self.array objectAtIndex:0];
    if ([tempScroll.type isEqualToString:@"TitleCard"]) {
        
        Scroll *scroll = [self.array objectAtIndex:button.tag - 5000];
        CrossSlipDetailViewController *crossSlipDetailVC = [[CrossSlipDetailViewController alloc] init];
        crossSlipDetailVC.address = scroll.api;
        [self.navigationController pushViewController:crossSlipDetailVC animated:YES];
        [crossSlipDetailVC release];
        
    } else if ([tempScroll.type isEqualToString:@"ImageCard"]) {
        Scroll *scroll = [self.array objectAtIndex:button.tag - 5000];
        GoodShopDetailViewController *goodShopDetailVC = [[GoodShopDetailViewController alloc] init];
        goodShopDetailVC.address = scroll.api;
        [self.navigationController pushViewController:goodShopDetailVC animated:YES];
        [goodShopDetailVC release];
    }

}

// 点击标题图片按钮事件
- (void)goodShopButtonAction:(UIButton *)button
{
    NSLog(@"优选好店");
    // 点击“优选好店”的时候执行
    Scroll *scroll = [self.array objectAtIndex:0];
    GoodShopViewController *goodShopVC = [[GoodShopViewController alloc] init];
    goodShopVC.address = scroll.api;
    [self.navigationController pushViewController:goodShopVC animated:YES];
    [goodShopVC release];
}

// 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Scroll *scroll = [self.array objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        
        if ([scroll.type isEqualToString:@"ImageCard"]) {
            return 75;
        } else {
            
            return 0;
        }
        
    }
    return 210 + 10;
}

- (void)dealloc
{
    [_tableView release];
    [_address release];
    [_activityOrNearShop release];
    [_refresh release];
    [_array release];
    [super dealloc];
}


// 定义处理数据的方法
- (void)handleData
{
    NSString *address = [NSString stringWithFormat:@"https://api.shiseapp.com%@", self.address];
    NSLog(@"处理数据地址%@", address);
    [NetHandler getDataWithUrl:address completion:^(NSData *data) {
        
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        
        
        NSArray *arr = [dic objectForKey:@"data"];
        self.refresh = [[dic objectForKey:@"pagination"] objectForKey:@"nextUrl"];
        [self.array removeAllObjects];
        for (NSDictionary *tempDic in arr) {
            
            Scroll *scroll = [[Scroll alloc] initWithDictionary:tempDic];
            [self.array addObject:scroll];
            [scroll release];
        }
        
        [self.tableView reloadData];
        
    }];
}

// 点击cell的时候执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    Scroll *scroll = [self.array objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        
        ApplyBuildActivityViewController *applyBuildActivityVC = [[ApplyBuildActivityViewController alloc] init];
        [self.navigationController pushViewController:applyBuildActivityVC animated:YES];
        [applyBuildActivityVC release];
        
    }
    
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
//warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
//    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    self.tableView.headerRefreshingText = @"正在刷新...";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在刷新...";
    
}

- (void)headerRereshing
{
    //    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.foodArr];
    ////    [self.foodArr removeAllObjects];
    //
    //    NSString *str = @"https://api.shiseapp.com/v2/timeline/";
    //    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
    //        NSError *resultError = nil;
    //        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
    //
    //        NSArray *arr = [result objectForKey:@"data"];
    
//    [self.array removeAllObjects];
    [self handleData];
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
    //        }];
}


- (void)footerRereshing
{
    NSString *str = self.refresh;
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
        
        NSArray *arr = [result objectForKey:@"data"];
        self.refresh = [[result objectForKey:@"pagination"] objectForKey:@"nextUrl"];
//        NSLog(@"********%@", self.refresh);
        
        
        // 新建一个数组用来存放上拉刷新后 请求的美食对象
        NSMutableArray *newFoodArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Food *food = [[Food alloc] initWithDictionary:dic];
            [newFoodArr addObject:food];
            [food release];
        }
        [self.array addObjectsFromArray:newFoodArr];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
        });
        
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
